{% extends "base.html" %}
{% block head %}
<style>
    :root {
        --primary-color: #1976d2;
        --primary-hover: #1565c0;
        --border-color: #e0e0e0;
        --light-gray: #f5f5f5;
        --text-color: #333;
        --shadow-color: rgba(0, 0, 0, 0.1);
    }

    body {
        color: var(--text-color);
        background-color: #f8f9fa;
    }

    .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }

    .card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
        padding: 20px;
        margin-bottom: 20px;
    }

    .card-header {
        margin: -20px -20px 20px;
        padding: 15px 20px;
        background: var(--light-gray);
        border-radius: 8px 8px 0 0;
        border-bottom: 1px solid var(--border-color);
    }

    .card-header h2 {
        margin: 0;
        font-size: 1.5rem;
        color: var(--primary-color);
    }

    /* 表格容器样式优化 */
    .table-wrapper {
        position: relative;
        margin: 20px -20px;
        background: white;
    }

    .table-container {
        width: 100%;
        overflow-x: auto;
        position: relative;
        max-height: 600px;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: var(--primary-color) var(--light-gray);
    }

    /* 自定义滚动条样式 */
    .table-container::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    .table-container::-webkit-scrollbar-track {
        background: var(--light-gray);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb {
        background: var(--primary-color);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb:hover {
        background: var(--primary-hover);
    }

    /* 滑动指示器 */
    .scroll-indicator {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: white;
        padding: 8px;
        border-radius: 4px;
        font-size: 12px;
        opacity: 0;
        transition: opacity 0.3s;
        pointer-events: none;
    }

    .scroll-indicator.visible {
        opacity: 1;
    }

    /* 表格样式优化 */
    .result-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        margin: 0;
        font-size: 12px;
        min-width: 1200px;
    }

    .result-table th {
        background: #e6f7ff;
        color: #0050b3;
        font-weight: normal;
        position: sticky;
        top: 0;
        z-index: 1;
        white-space: normal;
        word-break: break-word;
        min-width: 120px;
        height: auto;
        padding: 8px 6px;
        line-height: 1.4;
    }

    .result-table td {
        border: 1px solid #d9d9d9;
        padding: 6px 4px;
        text-align: left;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 150px;
    }

    .result-table tr:nth-child(even) {
        background: #f5faff;
    }

    .result-table td:hover {
        overflow: visible;
        white-space: normal;
        word-break: break-all;
        position: relative;
        z-index: 2;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    /* 分页控件美化 */
    .pagination-container {
        background: white;
        padding: 15px;
        border-top: 1px solid var(--border-color);
        border-radius: 0 0 8px 8px;
        display: flex;
        justify-content: flex-end;
        margin-top: 12px;
        gap: 8px;
    }

    .pagination {
        display: flex;
        justify-content: center;
        gap: 8px;
    }

    .pagination button {
        padding: 4px 12px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        background: #fff;
        cursor: pointer;
    }

    .pagination button:disabled {
        background: #f5f5f5;
        cursor: not-allowed;
    }

    .pagination button.active {
        background: #1890ff;
        color: white;
        border-color: #1890ff;
    }

    .pagination-ellipsis {
        color: #555;
        padding: 0 8px;
    }

    .btn {
        padding: 8px 16px;
        border-radius: 4px;
        border: none;
        cursor: pointer;
        font-weight: 500;
        transition: background-color 0.2s;
    }

    .btn-primary {
        background-color: var(--primary-color);
        color: white;
    }

    .btn-primary:hover {
        background-color: var(--primary-hover);
    }

    .btn:disabled {
        opacity: 0.65;
        cursor: not-allowed;
    }

    .spinner {
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #1976d2;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        display: none;
        margin-left: 10px;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .status-message {
        margin-top: 20px;
        padding: 15px;
        border-radius: 4px;
        display: none;
    }

    .status-message.error {
        background-color: #ffebee;
        color: #c62828;
        border: 1px solid #ffcdd2;
    }

    .status-message.success {
        background-color: #e8f5e9;
        color: #2e7d32;
        border: 1px solid #c8e6c9;
    }

    .folder-list.folder-list {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 10px;
    }

    .folder-item {
        background: var(--light-gray);
        padding: 8px 12px;
        border-radius: 4px;
        cursor: pointer;
        user-select: none;
        transition: background-color 0.2s;
    }

    .folder-item.selected {
        background: var(--primary-color);
        color: white;
    }

    .folder-item:hover {
        background-color: #f8f9fa;
    }

    .folder-item-left {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .folder-name {
        font-weight: 500;
    }

    .folder-status {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 0.9em;
    }

    .folder-status.exists {
        background-color: #e8f5e9;
        color: #2e7d32;
    }

    .folder-status.not-exists {
        background-color: #ffebee;
        color: #c62828;
    }

    .filter-area {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        margin: 20px 0;
    }

    .filter-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-bottom: 5px;
        border-bottom: 1px solid var(--border-color);
    }

    .filter-title {
        font-size: 16px;
        font-weight: 500;
        color: var(--text-color);
        margin: 0;
    }

    .filter-buttons {
        display: flex;
        gap: 10px;
    }

    .filter-content {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .filter-section {
        padding: 10px 15px;
        background: #f8f9fa;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
    }

    .filter-section-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
    }

    .relatives-section {
        margin-top: 10px;
        margin-bottom: 15px;
        padding: 15px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
        width: 100%;
    }

    .relatives-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 8px;
        margin-bottom: 10px;
        border-bottom: 1px solid #e0e0e0;
    }

    .relatives-section-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
    }

    .relatives-list {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 10px;
        padding: 10px;
        background: #f8f9fa;
        border-radius: 4px;
    }

    #relativesList {
        display: flex;
        flex-direction: column;
        gap: 15px;
        width: 100%;
    }

    .relative-item {
        display: flex;
        align-items: center;
        padding: 8px 12px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
        transition: all 0.2s ease;
    }

    .relative-item:hover {
        background: #f8f9fa;
        border-color: var(--primary-color);
    }

    .relative-item input[type="checkbox"] {
        margin-right: 8px;
        width: 16px;
        height: 16px;
        cursor: pointer;
    }

    .relative-item label {
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        color: var(--text-color);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .filter-label {
        display: block;
        font-size: 14px;
        font-weight: 500;
        color: #666;
        margin-bottom: 10px;
    }

    /* 按钮样式优化 */
    .btn-primary:disabled {
        background-color: #ccc;
        cursor: not-allowed;
    }

    /* 加载动画样式 */
    .loading {
        text-align: center;
        padding: 20px;
        display: none;
    }

    .loading.active {
        display: block;
    }

    .spinner {
        display: none;
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid var(--primary-color);
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-left: 10px;
        vertical-align: middle;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .filter-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .border-bottom {
        border-bottom: 1px solid #e0e0e0;
    }

    .filter-section-buttons {
        display: flex;
        gap: 8px;
    }

    .filter-section-buttons-input {
        display: flex;
        align-items: center;
        white-space: nowrap;
        gap: 5px;
        font-size: 12px;
    }

    .btn-sm {
        padding: 4px 8px;
        font-size: 12px;
    }

    .table-actions {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        margin-bottom: 15px;
        padding: 10px;
        background: white;
        border-radius: 4px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    .btn-outline-primary {
        background-color: white;
        color: var(--primary-color);
        border: 1px solid var(--primary-color);
    }

    .btn-outline-primary:hover {
        background-color: var(--primary-color);
        color: white;
    }

    /* 添加资产分类相关样式 */
    .asset-type-list {
        display: flex;
        gap: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 4px;
    }

    .asset-type-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
    }

    .asset-type-item input[type="checkbox"] {
        width: 16px;
        height: 16px;
        cursor: pointer;
    }

    .asset-type-item label {
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        color: var(--text-color);
    }

    .relatives-select-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background: white;
        border: 1px solid var(--primary-color);
        color: var(--primary-color);
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s;
    }

    .relatives-select-btn:hover {
        background: var(--primary-color);
        color: white;
    }

    .relatives-select-btn .selected-count {
        background: var(--primary-color);
        color: white;
        padding: 2px 6px;
        border-radius: 10px;
        font-size: 12px;
    }

    .relatives-select-btn:hover .selected-count {
        background: white;
        color: var(--primary-color);
    }

    /* 亲属选择模态框样式 */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
    }

    .modal-content {
        background-color: #fefefe;
        margin: 4% auto;
        padding: 25px;
        border: none;
        width: 90%;
        max-width: 1000px;
        border-radius: 8px;
        max-height: 85vh;
        overflow-y: auto;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: -25px -25px 20px;
        padding: 20px 25px;
        background: #f8f9fa;
        border-bottom: 1px solid #e0e0e0;
        border-radius: 8px 8px 0 0;
    }

    .modal-title {
        font-size: 1.25rem;
        font-weight: 500;
        color: var(--text-color);
        margin: 0;
    }

    .close-button {
        color: #666;
        font-size: 24px;
        font-weight: normal;
        cursor: pointer;
        transition: color 0.2s;
    }

    .close-button:hover {
        color: #333;
    }

    .relationship-tabs {
        margin: 0 -25px 20px;
        padding: 0 25px;
        background: #fff;
        border-bottom: 1px solid #e0e0e0;
        display: flex;
        gap: 0;
    }

    .relationship-tabs button {
        flex: 1;
        padding: 12px 24px;
        margin: 0;
        border: none;
        background: transparent;
        color: #666;
        cursor: pointer;
        font-size: 14px;
        font-weight: 500;
        position: relative;
        transition: all 0.2s;
        white-space: nowrap;
        text-align: center;
    }

    .relationship-tabs button:hover {
        color: var(--primary-color);
    }

    .relationship-tabs button.active {
        color: var(--primary-color);
    }

    .relationship-tabs button.active::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 0;
        width: 100%;
        height: 2px;
        background: var(--primary-color);
    }

    .relationship-panel {
        display: none;
        padding: 0;
        border: none;
        min-height: 300px;
        overflow-y: auto;
        max-height: calc(80vh - 200px);
    }

    .relationship-panel.active {
        display: block;
    }

    .relatives-section {
        margin-bottom: 20px;
        background: #fff;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        height: 100%;
    }

    .relatives-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        background: #f8f9fa;
        border-bottom: 1px solid #e0e0e0;
        border-radius: 8px 8px 0 0;
    }

    .relatives-section-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
    }

    .relatives-list {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;
        padding: 20px;
        background: #fff;
        border-radius: 0 0 8px 8px;
    }

    .relationship-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px 15px;
        background: #f8f9fa;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        transition: all 0.2s;
    }

    .relationship-item:hover {
        border-color: var(--primary-color);
        background: #fff;
    }

    .relationship-item input[type="checkbox"] {
        margin-right: 10px;
        width: 16px;
        height: 16px;
        cursor: pointer;
    }

    .relationship-item label {
        flex: 1;
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .relationship-type {
        font-size: 12px;
        color: #666;
        padding: 2px 8px;
        background: #e9ecef;
        border-radius: 12px;
        margin-left: 8px;
        white-space: nowrap;
    }

    .modal-footer {
        margin: 20px -25px -25px;
        padding: 15px 25px;
        background: #f8f9fa;
        border-top: 1px solid #e0e0e0;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        border-radius: 0 0 8px 8px;
    }

    .modal-footer .btn {
        min-width: 80px;
    }

    .filter-section-buttons .btn {
        padding: 6px 12px;
        font-size: 13px;
    }

    /* 为三商清单添加特殊布局 */
    #businessPanel .relatives-list {
        grid-template-columns: repeat(2, 1fr);
    }

    /* 调整三商清单项目的样式 */
    #businessPanel .relationship-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 15px;
        background: #f8f9fa;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        transition: all 0.2s;
        gap: 10px;
    }

    #businessPanel .relationship-item:hover {
        border-color: var(--primary-color);
        background: #fff;
    }

    #businessPanel .relationship-item label {
        flex: 1;
        margin: 0;
        font-size: 14px;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    #businessPanel .relationship-type {
        font-size: 12px;
        color: #666;
        padding: 2px 8px;
        background: #e9ecef;
        border-radius: 12px;
        white-space: nowrap;
        min-width: fit-content;
    }

    @media (max-width: 1200px) {
        .relatives-list {
            grid-template-columns: repeat(2, 1fr);
        }
        
        #businessPanel .relatives-list {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media (max-width: 768px) {
        .relatives-list {
            grid-template-columns: repeat(1, 1fr);
        }
        
        #businessPanel .relatives-list {
            grid-template-columns: repeat(1, 1fr);
        }
        
        .modal-content {
            width: 95%;
            margin: 2% auto;
        }
    }
</style>
{% endblock %}
{% block content %}
<div class="container">
    <div class="card">
        <div class="card-header">
            <h2>银行流水往来</h2>
        </div>
        <div class="card-body">
            <!-- 操作按钮 -->
            <div class="action-buttons">
                <button type="button" class="btn btn-primary" id="loadDataBtn">
                    加载已有数据
                    <div id="loadingSpinner" class="spinner"></div>
                </button>
                <!-- <button type="button" class="btn btn-primary" id="analyzeDataBtn">
                    分析数据
                    <div id="analyzeSpinner" class="spinner"></div>
                </button> -->
            </div>

            <!-- 状态消息 -->
            <div id="statusMessage" class="status-message"></div>
            
            <!-- 筛选区域 -->
            <div id="filterArea" class="filter-area">
                <div class="filter-section">
                    <div class="filter-section-header">
                        <div class="filter-section-title">
                            <label><input name="check_file_type" type="radio" value="1" checked/> 银行流水基础表（默认）</label>

                        </div>
                    </div>
                </div>
                <div class="filter-content">
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">
                                <label><input name="check_file_type" type="radio" value="2" /> 自定义银行流水表（自定义）</label>
                            </div>
                            <div class="filter-section-buttons" style="gap: 20px;">
                                <input type="hidden" name="filepath" />
                                <input type="file" name="custom_file" accept=".xlsx, .xls" multiple/>
                                <button type="button" class="btn btn-sm btn-primary" id="uploadCustomFileBtn">上传文件</button>
                            </div>
                        </div>
                    </div>
                    <div class="filter-section">
                        <div class="filter-section-header border-bottom">
                            <div class="filter-section-title">选择被审查人：</div>
                            <div class="filter-section-buttons">
                                <button type="button" class="btn btn-sm btn-primary" id="selectAllFoldersBtn">全选</button>
                                <button type="button" class="btn btn-sm btn-primary" id="deselectAllFoldersBtn">取消全选</button>
                            </div>
                        </div>
                        <div id="folderList" class="folder-list"></div>
                    </div>
                    <div class="filter-header">
                        <h3 class="filter-title">设定值</h3>
                    </div>
                    <!-- 亲属选择按钮 -->
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">1、发起方--亲属/特定关系人/三商选择：</div>
                            <button type="button" class="relatives-select-btn" id="relativesSelectBtn">
                                选择
                                <span class="selected-count" id="selectedRelativesCount">0</span>
                            </button>
                        </div>
                    </div>

                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">2、相对方--亲属/特定关系人/三商选择：</div>
                            <button type="button" class="relatives-select-btn" id="xiangduiRelativesSelectBtn">
                                选择
                                <span class="selected-count" id="xiangduiSelectedRelativesCount">0</span>
                            </button>
                        </div>
                    </div>

                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">3、资金走向 </div>
                            <div class="filter-section-buttons" >
                                <label><input name="money_type" type="checkbox" value="出" /> 出 </label>
                                <label><input name="money_type" type="checkbox" value="进" /> 进 </label>
                            </div>
                        </div>
                    </div>

                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">4、单笔特定数值区间：</div>
                            <div class="filter-section-buttons">
                                <input type="number" name="low_price" placeholder="最低值"/>-
                                <input type="number" name="top_price" placeholder="最高值"/>
                            </div>
                        </div>
                    </div>

                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">5、时间筛选:</div>
                            <div class="filter-section-buttons" style="flex-wrap: wrap;">
{#                                <input type="text" name="select_date" placeholder="时间筛选"/>#}
                                {# value: 设置默认日期（格式：YYYY-MM-DD）
                                {# min: 允许的最小日期
                                {# max: 允许的最大日期
                                {# step: 步进值（对于日期输入通常设为1）#}
                                <input type="date" id="appointment" name="select_date" value="YYYY-MM-DD" step="1">
                                <span>前后天数：</span><input type="number" name="before_day" placeholder="时间周期" value="10"/>
                            </div>
                        </div>
                    </div>
                    <div class="filter-header">
                        <h3 class="filter-title">规则选择</h3>
                    </div>
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">
                                <label><input name="rule-selecting" type="checkbox" value="1" /> 1、风险等级： </label>
                            </div>
                            <div class="filter-section-buttons" style="width: 80%; justify-content: flex-end;">
{#                                <label><input name="fengxian" type="radio" value="1" />低风险 </label>#}
{#                                <label><input name="fengxian" type="radio" value="2" />中风险 </label>#}
{#                                <label><input name="fengxian" type="radio" value="3" />高风险 </label>#}
                                <div class="filter-section-buttons-input">
                                    <input name="fengxian-selecting" type="checkbox" value="1" style="margin-left: 10px" />
                                    <input type="number" name="low_fengxian1" placeholder="最低值" value="10000"/> {{ '<低风险≤' }}
                                    <input type="number" name="top_fengxian1" placeholder="最高值" value="50000"/>
                                </div>
                                <div class="filter-section-buttons-input">
                                    <input name="fengxian-selecting" type="checkbox" value="2" style="margin-left: 10px" />
                                    <input type="number" name="low_fengxian2" placeholder="最低值" value="50000"/> {{ '<中风险≤' }}
                                    <input type="number" name="top_fengxian2" placeholder="最高值" value="100000"/>
                                </div>
                                <div class="filter-section-buttons-input">
                                    <input name="fengxian-selecting" type="checkbox" value="3" style="margin-left: 10px" />
                                    <input type="number" name="low_fengxian3" placeholder="最低值" value="100000"/> {{ '<高风险≤' }}
                                    <input type="number" name="top_fengxian3" placeholder="最高值" value=""/>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">
                                <label><input name="rule-selecting" type="checkbox" value="2" /> 2、一段时期内累计大金额: </label>
                            </div>
                            <div class="filter-section-buttons" >
                                <label><input name="day" type="radio" value="" />无</label>
                                <label><input name="day" type="radio" value="7" />7天</label>
                                <label><input name="day" type="radio" value="15" />15天 </label>
                                <label><input name="day" type="radio" value="30" />30天 </label>
                                <label><input name="day" type="radio" value="60" />60天 </label>
                                <label>
                                    <input name="day" type="radio" value="-1" />
                                    <input type="number" name="day_custom" placeholder="自定义" style="width: 85px; padding: 5px 9px;"/>天
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">
                                <label><input name="rule-selecting" type="checkbox" value="3" /> 3、不同人员雷同: </label>
                            </div>
                            <div class="filter-section-buttons" style="gap: 20px;">
                                <input type="radio" name="same_date" value="0"/><label> 无 </label>
                                <input type="radio" name="same_date" value="1"/><label> ①日期相同，例如都是2018-03-08 </label>

                                <input type="radio" name="same_date" value="2"/><label> ②IP地址相同（前三的地址段一致） </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 亲属选择模态框 -->
            <div id="relativesModal" class="modal" >
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">选择关系人</h3>
                        <span class="close-button" id="closeRelativesModal">&times;</span>
                    </div>
                    
                    <!-- 更新标签页切换按钮 -->
                    <div class="relationship-tabs" data-num="0">
                        <button type="button" class="active" data-tab="relatives">亲属关系</button>
                        <button type="button" data-tab="specific">特定关系人</button>
                        <button type="button" data-tab="business">三商清单</button>
                    </div>
                    
                    <!-- 亲属关系面板 -->
                    <div id="relativesPanel" class="relationship-panel relativesPanel_checkbok active" data-num="0"></div>
                    
                    <!-- 特定关系人面板 -->
                    <div id="specificPanel" class="relationship-panel specificPanel_checkbok" data-num="0"></div>

                    <!-- 三商清单面板 -->
                    <div id="businessPanel" class="relationship-panel bussness_checkbok" data-num="0"></div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-primary" id="cancelRelativesSelection">取消</button>
                        <button type="button" class="btn btn-primary" id="confirmRelativesSelection">确定</button>
                    </div>
                </div>
            </div>

            <div id="relativesModal1" class="modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">选择关系人</h3>
                        <span class="close-button" id="closeRelativesModal1">&times;</span>
                    </div>
                    
                    <!-- 更新标签页切换按钮 -->
                    <div class="relationship-tabs" data-num="1">
                        <button type="button" class="active" data-tab="relatives">亲属关系</button>
                        <button type="button" data-tab="specific">特定关系人</button>
                        <button type="button" data-tab="business">三商清单</button>
                    </div>
                    
                    <!-- 亲属关系面板 -->
                    <div id="relativesPanel1" class="relationship-panel relativesPanel_checkbok active" data-num="1"></div>
                    
                    <!-- 特定关系人面板 -->
                    <div id="specificPanel1" class="relationship-panel specificPanel_checkbok" data-num="1"></div>


                    <!-- 三商清单面板 -->
                    <div id="businessPanel1" class="relationship-panel bussness_checkbok" data-num="1"></div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-primary" id="cancelRelativesSelection1">取消</button>
                        <button type="button" class="btn btn-primary" id="confirmRelativesSelection1">确定</button>
                    </div>
                </div>
            </div>

            <!-- 表格操作按钮 -->
            <div class="table-actions">
                <button type="button" class="btn btn-primary" id="applyFilterBtn">应用筛选</button>
                <button type="button" class="btn btn-outline-primary" id="cancelFilterBtn">取消筛选</button>
                <button type="button" class="btn btn-primary" id="applyFilterBtn1">下载excel</button>
            </div>

            <!-- 加载动画 -->
            <div id="loading" class="loading">
                正在加载数据，请稍候...
            </div>

            <!-- 结果表格 -->
            <div id="resultContainer" class="card" style="display: none;">
                <div class="table-wrapper">
                    <div class="table-container">
                        <div class="scroll-indicator">向右滑动查看更多</div>
                        <table class="result-table">
                            <thead>
                                <tr id="tableHeader"></tr>
                            </thead>
                            <tbody id="tableBody"></tbody>
                        </table>
                    </div>
                    <div class="pagination-container">
                        <div class="pagination" id="pagination"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // document.querySelectorAll('input[name="fengxian"]').forEach(function(radio) {
        //     radio.addEventListener('change', function() {
        //         console.log('Selected radio:', this.value);
        //         if (this.value == 1) {
        //             document.querySelector('input[name="low_price"]').value = 10000
        //             document.querySelector('input[name="top_price"]').value = 50000
        //         }

        //         if (this.value == 2) {
        //             document.querySelector('input[name="low_price"]').value = 50000
        //             document.querySelector('input[name="top_price"]').value = 100000
        //         }

        //         if (this.value == 3) {
        //             document.querySelector('input[name="low_price"]').value = 100000
        //             document.querySelector('input[name="top_price"]').value = ''
        //         }
        //     });
        // });
        // 获取DOM元素
        const loadDataBtn = document.getElementById('loadDataBtn');
        const analyzeDataBtn = document.getElementById('analyzeDataBtn');
        const loadingSpinner = document.getElementById('loadingSpinner');
        const analyzeSpinner = document.getElementById('analyzeSpinner');
        const statusMessage = document.getElementById('statusMessage');
        const filterArea = document.getElementById('filterArea');
        const folderList = document.getElementById('folderList');
        const applyFilterBtn = document.getElementById('applyFilterBtn');
        const selectAllBtn = document.getElementById('selectAllBtn');
        const deselectAllBtn = document.getElementById('deselectAllBtn');

        

        let currentPage = 1;
        let totalPages = 1;
        let cachedData = null;
        let itemsPerPage = 20;

        let api_url = '/bank-flow'

        // 存储亲属数据的Map
        let relativesMap = new Map();
        const relativesModal = document.getElementById('relativesModal');
        const relativesSelectBtn = document.getElementById('relativesSelectBtn');
        const closeRelativesModal = document.getElementById('closeRelativesModal');
        const cancelRelativesSelection = document.getElementById('cancelRelativesSelection');
        const confirmRelativesSelection = document.getElementById('confirmRelativesSelection');
        const selectedRelativesCount = document.getElementById('selectedRelativesCount');
        // 存储关系数据的Map
        let specificRelationsMap = new Map();
        let businessListMap = new Map();
        let persistentSelectedRelatives = new Set();
        let persistentSelectedSpecific = new Set();
        let persistentSelectedBusiness = new Set();
        let tempSelectedRelatives = new Set();
        let tempSelectedSpecific = new Set();
        let tempSelectedBusiness = new Set();
        let currentTab = 'relatives';


    // 标签页切换事件处理
    document.querySelectorAll('.relationship-tabs button').forEach(button => {
        button.addEventListener('click', (e) => {
            document.querySelectorAll('.relationship-tabs button').forEach(btn => {
                btn.classList.remove('active');
            });
            e.target.classList.add('active');

            document.querySelectorAll('.relationship-panel').forEach(panel => {
                panel.classList.remove('active');
                panel.style.display = 'none';
            });
            let num = e.target.parentElement.dataset.num;

            const tab = e.target.dataset.tab;
            let targetPanel;
            switch(tab) {
                case 'relatives':
                    targetPanel =  $('.relativesPanel_checkbok:eq('+num+')');
                    break;
                case 'specific':
                    targetPanel =  $('.specificPanel_checkbok:eq('+num+')');
                    break;
                case 'business':
                    targetPanel =  $('.bussness_checkbok:eq('+num+')');
                    break;
            }

            if (targetPanel) {
                targetPanel.addClass('active');
                targetPanel.css('display', 'block');
                currentTab = tab;
                window.dispatchEvent(new Event('resize'));
            }
        });
    });

    function showRelationsList()
    {

    }

    // 更新关系列表函数
    function updateRelationshipList(num=0) {
        const relativesPanel = document.getElementById('relativesPanel');
        const specificPanel = document.getElementById('specificPanel');
        const businessPanel = document.getElementById('businessPanel');
        
        const selectedFolders = getSelectedFolders();

        // 清空所有面板
        $('.relativesPanel_checkbok:eq('+num+')').html('');
        $('.specificPanel_checkbok:eq('+num+')').html('');
        $('.bussness_checkbok:eq('+num+')').html('');

        if (selectedFolders.length === 0) {
            const message = '<div style="text-align: center; padding: 20px;">请先选择被审查人</div>';
            $('.relativesPanel_checkbok:eq('+num+')').html(message);
            $('.specificPanel_checkbo:eq('+num+')').html(message);
            $('.bussness_checkbok:eq('+num+')').html(message);
            return;
        }

        // 更新亲属关系面板
        selectedFolders.forEach(folderName => {
            const relatives = relativesMap.get(folderName) || [];
            if (relatives.length > 0) {
                appendRelationshipSection(relativesPanel, folderName, relatives, 'relatives', '.relativesPanel_checkbok:eq('+num+')', num);
            }
        });

        // 更新特定关系人面板
        selectedFolders.forEach(folderName => {
            const specific = specificRelationsMap.get(folderName) || [];
            if (specific.length > 0) {
                appendRelationshipSection(specificPanel, folderName, specific, 'specific', '.specificPanel_checkbok:eq('+num+')', num);
            }
        });

        // 更新三商清单面板
        selectedFolders.forEach(folderName => {
            const business = businessListMap.get(folderName) || [];
            if (business.length > 0) {
                appendRelationshipSection(businessPanel, folderName, business, 'business', '.bussness_checkbok:eq('+num+')', num);
            }
        });

        // 确保当前活动面板可见
        const activeTab = document.querySelector('.relationship-tabs button.active');
        
        if (activeTab) {
            const tab = activeTab.dataset.tab;
            let targetPanel;
            switch(tab) {
                case 'relatives':
                    targetPanel =  $('.relativesPanel_checkbok:eq('+num+')');
                    break;
                case 'specific':
                    targetPanel =  $('.specificPanel_checkbok:eq('+num+')');
                    break;
                case 'business':
                    targetPanel =  $('.bussness_checkbok:eq('+num+')');
                    break;
            }
            if (targetPanel) {
                $('.relationship-tabs:eq('+num+') button:eq(0)').addClass('active');
                targetPanel.addClass('active');
                targetPanel.css('display', 'block');
            }
        }

        updateSelectedCount();
    }

    // 添加关系部分到面板
    function appendRelationshipSection(panel, folderName, relationships, type,classNames_checkbox, num) {
        let section = document.createElement('div');
        section.className = 'relatives-section';

        // 创建区域标题和按钮
        let header = document.createElement('div');
        header.className = 'relatives-section-header';

        let title = document.createElement('div');
        title.className = 'relatives-section-title';
        title.textContent = `${folderName} 的${type === 'relatives' ? '亲属' : type === 'specific' ? '特定关系人' : '三商清单'}`;

        let buttonGroup = document.createElement('div');
        buttonGroup.className = 'filter-section-buttons';

        let selectAllBtn = document.createElement('button');
        selectAllBtn.type = 'button';
        selectAllBtn.className = 'btn btn-sm btn-primary';
        selectAllBtn.textContent = '全选';
        selectAllBtn.onclick = () => selectAllInSection(folderName, type, num);

        let deselectAllBtn = document.createElement('button');
        deselectAllBtn.type = 'button';
        deselectAllBtn.className = 'btn btn-sm btn-primary';
        deselectAllBtn.textContent = '取消全选';
        deselectAllBtn.onclick = () => deselectAllInSection(folderName, type, num);

        buttonGroup.appendChild(selectAllBtn);
        buttonGroup.appendChild(deselectAllBtn);
        header.appendChild(title);
        header.appendChild(buttonGroup);
        section.appendChild(header);

        // 创建关系列表
        let list = document.createElement('div');
        list.className = 'relatives-list';
        list.id = `${type}-${folderName}`;

        relationships.forEach(item => {
            let itemDiv = document.createElement('div');
            itemDiv.className = 'relationship-item';
            
            let checkboxContainer = document.createElement('div');
            checkboxContainer.style.flex = '1';
            
            let checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = `${type}${num}-${folderName}-${item[0]}`;
            checkbox.value = item[0];
            checkbox.dataset.folder = folderName;
            checkbox.dataset.type = type;
            
            let label = document.createElement('label');
            label.htmlFor = checkbox.id;
            label.textContent = `${item[0]}（${item[1]}）`;
            
            checkboxContainer.appendChild(checkbox);
            checkboxContainer.appendChild(label);
            itemDiv.appendChild(checkboxContainer);

            // 如果是特定关系人/三商清单，添加类型标签
            if (type === 'specific' && item[2]) {
                let typeSpan = document.createElement('span');
                typeSpan.className = 'relationship-type';
                typeSpan.textContent = item[2];
                itemDiv.appendChild(typeSpan);
            }

            list.appendChild(itemDiv);
        });

        section.appendChild(list);
        // panel.appendChild(section);
        $(classNames_checkbox).append(section)
        // panel.append(section); // 直接追加到 panel
        // $(classNames_checkbox).each(function(index,element){
        //     $(this).append(section);
        // })
    }

    // 更新选中计数
    const xiangduiSelectedRelativesCount = document.getElementById('xiangduiSelectedRelativesCount');
    function updateSelectedCount(num) {
        
        if (num == 1) {
            const checkedRelatives = document.querySelectorAll('#relativesModal1 #relativesPanel input[type="checkbox"]:checked').length;
            const checkedSpecific = document.querySelectorAll('#relativesModal1 #specificPanel input[type="checkbox"]:checked').length;
            const checkedBusiness = document.querySelectorAll('#relativesModal1 #businessPanel input[type="checkbox"]:checked').length;
            xiangduiSelectedRelativesCount.textContent = checkedRelatives + checkedSpecific + checkedBusiness;
        } else {
            const checkedRelatives = document.querySelectorAll('#relativesModal #relativesPanel input[type="checkbox"]:checked').length;
            const checkedSpecific = document.querySelectorAll('#relativesModal #specificPanel input[type="checkbox"]:checked').length;
            const checkedBusiness = document.querySelectorAll('#relativesModal #businessPanel input[type="checkbox"]:checked').length;
            selectedRelativesCount.textContent = checkedRelatives + checkedSpecific + checkedBusiness;
        }
    }

    // 全选指定部分
    function selectAllInSection(folderName, type, num) {
        let modalId = '';
        if (num == 0) {
            modalId = '#relativesModal';
        } else {
            modalId = '#relativesModal1';
        }
        const selector = `${modalId} #${type}-${folderName} input[type="checkbox"]`;
        const checkboxes = document.querySelectorAll(selector);
        checkboxes.forEach(cb => {
            cb.checked = true;
        });
        updateSelectedCount(num);
    }

    // 取消全选指定部分
    function deselectAllInSection(folderName, type, num) {
        let modalId = '';
        if (num == 0) {
            modalId = '#relativesModal';
        } else {
            modalId = '#relativesModal1';
        }
        const selector = `${modalId} #${type}-${folderName} input[type="checkbox"]`;
        const checkboxes = document.querySelectorAll(selector);
        checkboxes.forEach(cb => {
            cb.checked = false;
        });
        updateSelectedCount(num);
    }

    $('#xiangduiRelativesSelectBtn').on('click', function name() {
        $('#relativesModal1').css('display', 'block');
        updateRelationshipList(1);
    })

    // 修改打开模态框的处理
    relativesSelectBtn.addEventListener('click', () => {
        // 更新关系列表
        updateRelationshipList(0);
        
        // 保存当前选中状态
        tempSelectedRelatives = new Set(persistentSelectedRelatives);
        tempSelectedSpecific = new Set(persistentSelectedSpecific);
        tempSelectedBusiness = new Set(persistentSelectedBusiness);
        
        // 显示模态框
        relativesModal.style.display = 'block';
        
        // 确保默认显示第一个标签页
        const firstTab = document.querySelector('.relationship-tabs button');
        if (firstTab) {
            firstTab.click();
        }
    });

    // 修改确认按钮的处理
    confirmRelativesSelection.addEventListener('click', () => {
        // 更新持久化的选中状态
        persistentSelectedRelatives = new Set(
            Array.from(document.querySelectorAll('#relativesPanel input[type="checkbox"]:checked'))
                .map(cb => cb.value)
        );
        persistentSelectedSpecific = new Set(
            Array.from(document.querySelectorAll('#specificPanel input[type="checkbox"]:checked'))
                .map(cb => cb.value)
        );
        persistentSelectedBusiness = new Set(
            Array.from(document.querySelectorAll('#businessPanel input[type="checkbox"]:checked'))
                .map(cb => cb.value)
        );
        selectedRelativesCount.textContent = 
            persistentSelectedRelatives.size + 
            persistentSelectedSpecific.size + 
            persistentSelectedBusiness.size;
        relativesModal.style.display = 'none';
    });
    let xiangduiSelectedRelativesData = [];
    $('#confirmRelativesSelection1').on('click',function(){
        $('#relativesModal1').css('display','none');
        xiangduiSelectedRelativesData = Array.from(document.querySelectorAll('#relativesModal1 input[type="checkbox"]:checked'))
                .map(cb => cb.value);
                console.log(xiangduiSelectedRelativesData)
        $('#xiangduiSelectedRelativesCount').text(xiangduiSelectedRelativesData.length);
    })

    $('#uploadCustomFileBtn').on('click', function () {
            uploadFile();
        });

        function uploadFile()
        {
            const fileInput = document.querySelector('input[name="custom_file"]');
            const file = fileInput.files[0];
            if (!file) {
                alert('请选择文件');
                return;
            }
            const formData = new FormData();
            formData.append('file', file);
            // jq实现上传文件到$(api_url)
            $.ajax({
                url: `/asset-situation/upload-file`,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {
                    alert(data.message);
                    if (data.success) {
                        $('input[name="filepath"]').val(data.file_path);
                    }
                },
                error: function() {
                    console.log('上传失败');
                }
            });
        }

    // 修改取消按钮的处理
    cancelRelativesSelection.addEventListener('click', () => {
        // 恢复之前的选中状态
        document.querySelectorAll('#relativesPanel input[type="checkbox"]').forEach(cb => {
            cb.checked = tempSelectedRelatives.has(cb.value);
        });
        document.querySelectorAll('#specificPanel input[type="checkbox"]').forEach(cb => {
            cb.checked = tempSelectedSpecific.has(cb.value);
        });
        document.querySelectorAll('#businessPanel input[type="checkbox"]').forEach(cb => {
            cb.checked = tempSelectedBusiness.has(cb.value);
        });
        relativesModal.style.display = 'none';
    });

    // 点击模态框外部关闭
    window.addEventListener('click', (event) => {
        if (event.target === relativesModal) {
            relativesModal.style.display = 'none';
            $('#relativesModal1').css('display','none');
        }
    });

    // 关闭按钮事件
    closeRelativesModal.addEventListener('click', () => {
        relativesModal.style.display = 'none';
    });

    $('#closeRelativesModal1').on('click',function(){
        $('#relativesModal1').css('display','none');
    })

    $('#cancelRelativesSelection1').on('click',function(){
        $('#relativesModal1').css('display','none');
    })

    // 获取选中的文件夹
    function getSelectedFolders() {
        const checkboxes = folderList.querySelectorAll('input[type="checkbox"]:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }

    // 全选文件夹
    function selectAllFolders() {
        const checkboxes = folderList.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = true;
        });
        // updateRelationshipList(0);
    }

    // 取消全选文件夹
    function deselectAllFolders() {
        const checkboxes = folderList.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = false;
        });
        // updateRelationshipList();
    }

    // 绑定按钮事件
    loadDataBtn.addEventListener('click', loadFullData);
    document.getElementById('selectAllFoldersBtn').addEventListener('click', selectAllFolders);
    document.getElementById('deselectAllFoldersBtn').addEventListener('click', deselectAllFolders);

        // 加载数据和文件夹列表
        async function loadFullData() {
           try {
                loadingSpinner.style.display = 'inline-block';
                loadDataBtn.disabled = true;
                document.getElementById('loading').classList.add('active');

                const response = await fetch(`${api_url}/check-data`);
                const result = await response.json();

                if (result.exists) {
                    statusMessage.textContent = '数据加载成功';
                    statusMessage.className = 'status-message success';
                    statusMessage.style.display = 'block';

                    // 清除现有数据
                    relativesMap.clear();
                    specificRelationsMap.clear();
                    businessListMap.clear();
                    
                    // 显示文件夹列表
                    folderList.innerHTML = '';
                    result.folders.forEach(folder => {
                        const folderItem = document.createElement('div');
                        folderItem.className = 'folder-item';
                        
                        const checkbox = document.createElement('input');
                        checkbox.type = 'checkbox';
                        checkbox.id = folder.name;
                        checkbox.value = folder.name;
                        // checkbox.addEventListener('change', () => {
                        //     console.log(`[DEBUG] 文件夹 ${folder.name} 的选中状态改变`);
                            // updateRelationshipList();
                        // });
                        
                        const label = document.createElement('label');
                        label.htmlFor = folder.name;
                        label.textContent = folder.name;
                        
                        folderItem.appendChild(checkbox);
                        folderItem.appendChild(label);
                        folderList.appendChild(folderItem);

                        // 分别存储不同类型的关系数据
                        if (folder.relatives && Array.isArray(folder.relatives)) {
                            relativesMap.set(folder.name, folder.relatives);
                        }
                        if (folder.business && Array.isArray(folder.business)) {
                            businessListMap.set(folder.name, folder.business);
                        }

                        if (folder.special && Array.isArray(folder.special)) {
                            specificRelationsMap.set(folder.name, folder.special);
                        }
                        
                    });

                    filterArea.style.display = 'block';
                } else {
                    statusMessage.textContent = result.error || '加载数据失败';
                    statusMessage.className = 'status-message error';
                    statusMessage.style.display = 'block';
                }
            } catch (error) {
                console.error('Error:', error);
                statusMessage.textContent = '加载数据时出错';
                statusMessage.className = 'status-message error';
                statusMessage.style.display = 'block';
            } finally {
                loadingSpinner.style.display = 'none';
                loadDataBtn.disabled = false;
                document.getElementById('loading').classList.remove('active');
            }
        }

        // 分析数据
        async function analyzeData() {
            try {
                analyzeSpinner.style.display = 'inline-block';
                analyzeDataBtn.disabled = true;
                statusMessage.style.display = 'none';

                const response = await fetch(`${api_url}/analyze-data`, {
                    method: 'POST'
                });
                const result = await response.json();

                if (result.success) {
                    statusMessage.textContent = '数据分析完成，正在重新加载数据...';
                    statusMessage.className = 'status-message success';
                    await loadFullData();
                } else {
                    statusMessage.textContent = result.error || '数据分析失败';
                    statusMessage.className = 'status-message error';
                }
                statusMessage.style.display = 'block';
            } catch (error) {
                console.error('Error:', error);
                statusMessage.textContent = '分析数据时出错';
                statusMessage.className = 'status-message error';
                statusMessage.style.display = 'block';
            } finally {
                analyzeSpinner.style.display = 'none';
                analyzeDataBtn.disabled = false;
            }
        }


        // 全选指定文件夹的亲属
        // function selectAllRelativesInFolder(folderName) {
        //     const checkboxes = document.querySelectorAll(`#relatives-${folderName} input[type="checkbox"]`);
        //     checkboxes.forEach(cb => {
        //         cb.checked = true;
        //     });
        // }

        // 取消全选指定文件夹的亲属
        // function deselectAllRelativesInFolder(folderName) {
        //     const checkboxes = document.querySelectorAll(`#relatives-${folderName} input[type="checkbox"]`);
        //     checkboxes.forEach(cb => {
        //         cb.checked = false;
        //     });
        // }

        // 全选指定文件夹的亲属
        // function selectAllRelatives1InFolder(folderName) {
        //     const checkboxes = document.querySelectorAll(`#relatives-${folderName}1 input[type="checkbox"]`);
        //     checkboxes.forEach(cb => {
        //         cb.checked = true;
        //     });
        // }

        // 取消全选指定文件夹的亲属
        // function deselectAllRelatives1InFolder(folderName) {
        //     const checkboxes = document.querySelectorAll(`#relatives-${folderName}1 input[type="checkbox"]`);
        //     checkboxes.forEach(cb => {
        //         cb.checked = false;
        //     });
        // }

        // 全选所有亲属
        // function selectAllRelatives() {
        //     const selectedFolders = getSelectedFolders();
        //     selectedFolders.forEach(folderName => {
        //         selectAllRelativesInFolder(folderName);
        //     });
        // }

        // 取消全选所有亲属
        // function deselectAllRelatives() {
        //     const selectedFolders = getSelectedFolders();
        //     selectedFolders.forEach(folderName => {
        //         deselectAllRelativesInFolder(folderName);
        //     });
        // }

        // 获取所有选中的亲属
        // function getSelectedRelatives() {
        //     const checkboxes = document.querySelectorAll('#relativesList input[type="checkbox"]:checked');
        //     return Array.from(checkboxes).map(cb => cb.value);
        // }

        // function getSelectedRelatives1() {
        //     const checkboxes = document.querySelectorAll('#relativesList1 input[type="checkbox"]:checked');
        //     return Array.from(checkboxes).map(cb => cb.value);
        // }

        // 获取选中的文件夹
        function getSelectedFolders() {
            const checkboxes = folderList.querySelectorAll('input[type="checkbox"]:checked');
            return Array.from(checkboxes).map(cb => cb.value);
        }

        // 全选所有
        function selectAll() {
            selectAllFolders();
            selectAllRelatives();
        }

        // 取消全选所有
        // function deselectAll() {
        //     deselectAllFolders();
        //     deselectAllRelatives();
        // }

        // 全选文件夹
        function selectAllFolders() {
            const checkboxes = folderList.querySelectorAll('input[type="checkbox"]');
            checkboxes.forEach(cb => {
                cb.checked = true;
            });
            updateRelativesList();
        }

        // 取消全选文件夹
        function deselectAllFolders() {
            const checkboxes = folderList.querySelectorAll('input[type="checkbox"]');
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
            updateRelativesList();
        }

        // 获取选中的资产分类
        function getSelectedAssetTypes() {
            const checkboxes = document.querySelectorAll('#assetTypeList input[type="checkbox"]:checked');
            return Array.from(checkboxes).map(cb => cb.value);
        }

        // 全选资产分类
        function selectAllAssetTypes() {
            const checkboxes = document.querySelectorAll('#assetTypeList input[type="checkbox"]');
            checkboxes.forEach(cb => {
                cb.checked = true;
            });
        }

        // 取消全选资产分类
        function deselectAllAssetTypes() {
            const checkboxes = document.querySelectorAll('#assetTypeList input[type="checkbox"]');
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
        }
        $('#applyFilterBtn1').on('click', function name(params) {
            applyFilter(1)
        })

        // 修改应用筛选函数
        async function applyFilter(is_excel) {

            const selectedFolders = getSelectedFolders();
            let selectedRelatives = Array.from(document.querySelectorAll('#relativesModal input[type="checkbox"]:checked'))
                .map(cb => cb.value);
            let selectedRelatives1 = Array.from(document.querySelectorAll('#relativesModal1 input[type="checkbox"]:checked'))
                .map(cb => cb.value);
            
            const low_price = document.querySelector('input[name="low_price"]').value
            const top_price = document.querySelector('input[name="top_price"]').value
            let money_type = Array.from(document.querySelectorAll('input[name="money_type"]:checked'))
                .map(cb => cb.value);
            let select_date = $('input[name="select_date"]').val();
            // console.log(selectedRelatives1)
            // const selectedAssetTypes = getSelectedAssetTypes();

            let ruleSelecting = Array.from(document.querySelectorAll('input[name="rule-selecting"]:checked')).map(cb => cb.value);
            let fengxianSelecting = Array.from(document.querySelectorAll('input[name="fengxian-selecting"]:checked')).map(cb => cb.value);
            let low_fengxian1 = $('input[name="low_fengxian1"]').val();
            let top_fengxian1 = $('input[name="top_fengxian1"]').val();
            let low_fengxian2 = $('input[name="low_fengxian2"]').val();
            let top_fengxian2 = $('input[name="top_fengxian2"]').val();
            let low_fengxian3 = $('input[name="low_fengxian3"]').val();
            let top_fengxian3 = $('input[name="top_fengxian3"]').val();
            let before_day = $('input[name="before_day"]').val();
            
           
            
            if (selectedFolders.length === 0) {
                alert('请至少选择一个被审查人');
                return;
            }
            
            if (selectedRelatives.length === 0) {
                // alert('请至少选择一个发起方');
                // selectedRelatives = Array.from(document.querySelectorAll('#relativesModal input[type="checkbox"]'))
                // .map(cb => cb.value);
                // selectedRelatives = [];
                // $.each(selectedFolders, function (index,folder) {
                //     relatives = relativesMap.get(folder);
                //     $.each(relatives, function (relativeIndex, relative) {
                //       selectedRelatives.push(relative[0]);
                //     })

                //     businessList = businessListMap.get(folder);
                //     $.each(businessList, function (relativeIndex, relative) {
                //       selectedRelatives.push(relative[0]);
                //     })

                //     specificRelations = specificRelationsMap.get(folder);
                //     $.each(specificRelations, function (relativeIndex, relative) {
                //       selectedRelatives.push(relative[0]);
                //     })
                // });
            }

            if (selectedRelatives1.length === 0) {
                // alert('请至少选择一个相对方');
                // selectedRelatives1 = [];
                // $.each(selectedFolders, function (index,folder) {
                //     relatives = relativesMap.get(folder);
                //     $.each(relatives, function (relativeIndex, relative) {
                //       selectedRelatives1.push(relative[0]);
                //     })

                //     businessList = businessListMap.get(folder);
                //     $.each(businessList, function (relativeIndex, relative) {
                //       selectedRelatives1.push(relative[0]);
                //     })

                //     specificRelations = specificRelationsMap.get(folder);
                //     $.each(specificRelations, function (relativeIndex, relative) {
                //       selectedRelatives1.push(relative[0]);
                //     })
                // });
            }
            // if (!low_price && !top_price) {
            //     alert('请给出单笔资金数值区间')
            //     return false
            // }
            

            if (money_type.length === 0) {
                // alert('请选择资金走向')
                // return false
                money_type = ['出', '进'];
            }

            // if (!select_date) {
            //     alert('请选择时间')
            //     return false
            // }

            let fengxian = $('input[name="fengxian"]:checked').val();
            let day = $('input[name="day"]:checked').val();
            let same_data = $('input[name="same_data"]:checked').val();
            let same_date = $('input[name="same_date"]:checked').val();
            let same_ip = $('input[name="same_ip"]:checked').val();
            let filepath = $('input[name="filepath"]').val();
            let check_file_type = $('input[name="check_file_type"]:checked').val();
            try {
                document.getElementById('loading').classList.add('active');
                
                const params = new URLSearchParams();
                if (low_price) {
                    params.append('low_price', low_price);
                }
                if (top_price) {
                    params.append('top_price', top_price);
                }
                selectedFolders.forEach(folder => {
                    params.append('folders', folder);
                });
                selectedRelatives.forEach(relative => {
                    params.append('relatives', relative);
                });
                if (before_day) {
                    params.append('before_day', before_day);
                }
                if (is_excel == 1) {
                    params.append('is_excel', is_excel)
                }
                if (same_date) {
                    params.append('same_date', same_date[0]);
                }
                if (same_ip) {
                    params.append('same_ip', same_ip[0]);
                }
                if (filepath) {
                    params.append('filepath', filepath);
                }

                if (check_file_type) {
                    params.append('check_file_type', check_file_type);
                }
                selectedRelatives1.forEach(relative => {
                    params.append('relatives1', relative);
                });
                money_type.forEach(item => {
                    params.append('money_type', item);
                });

                ruleSelecting.forEach(item => {
                    params.append('rule_selecting', item);
                });

                fengxianSelecting.forEach(item => {
                    params.append('fengxian_selecting', item);
                });

                if (select_date) {
                    params.append('select_date', select_date);
                }
                // if (fengxian) {
                //     params.append('fengxian', fengxian);
                // }
                if (day) {
                    if (day == -1) {
                        day = $('input[name="day_custom"]').val();
                    }
                    params.append('day', day);
                }
                // if (same_data) {
                //     params.append('same_data', same_data);
                // }

                 if (low_fengxian1) {
                    params.append('low_fengxian1', low_fengxian1);
                }
                if (top_fengxian1) {
                    params.append('top_fengxian1', top_fengxian1);
                }
                if (low_fengxian2) {
                    params.append('low_fengxian2', low_fengxian2);
                }
                if (top_fengxian2) {
                    params.append('top_fengxian2', top_fengxian2);
                }
                if (low_fengxian3) {
                    params.append('low_fengxian3', low_fengxian3);
                }
                if (top_fengxian3) {
                    params.append('top_fengxian3', top_fengxian3);
                }

                if (is_excel == 1) {
                    const downloadUrl = `${api_url}/get-analysis?${params.toString()}`;
                    
                    // 使用 fetch 发起请求，以便可以处理响应头
                    fetch(downloadUrl)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('下载失败');
                            }
                            // 检查响应的 Content-Type
                            const contentType = response.headers.get('content-type');
                            if (contentType.includes('application/json')) {
                                // 如果返回的是 JSON，说明可能出错，解析并抛出错误
                                return response.json().then(data => {
                                    throw new Error(data.error || '获取的数据格式错误，期望 Excel 文件但得到 JSON');
                                });
                            }
                            return response.blob();
                        })
                        .then(blob => {
                            // 创建一个临时的 URL 对象
                            const url = URL.createObjectURL(blob);
                            const link = document.createElement('a');
                            link.href = url;
                            // 添加 download 属性，确保浏览器执行下载而非跳转
                            link.download = '银行流水往来分析结果.xlsx'; 
                            link.style.display = 'none';
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                            // 释放临时 URL
                            URL.revokeObjectURL(url);

                            statusMessage.textContent = '文件下载成功';
                            statusMessage.className = 'status-message success';
                            statusMessage.style.display = 'block';
                        })
                        .catch(error => {
                            console.error('下载出错:', error);
                            statusMessage.textContent = `文件下载失败: ${error.message}`;
                            statusMessage.className = 'status-message error';
                            statusMessage.style.display = 'block';
                        });
                } else {
                    const response = await fetch(`${api_url}/get-analysis?${params.toString()}`);

                    const result = await response.json();

                    if (result.success && is_excel !=1 ) {
                        cachedData = result.data;
                        totalPages = Math.ceil(cachedData.length / itemsPerPage);
                        currentPage = 1;
                        displayPageData();
                    } else {
                        alert(result.error || '获取数据失败');
                    }
                }
                
            } catch (error) {
                console.error('Error:', error);
                alert('筛选数据时出错');
            } finally {
                document.getElementById('loading').classList.remove('active');
            }
        }

        // 显示分页数据
        function displayPageData(page = currentPage) {
            if (!cachedData) return;

            const start = (page - 1) * itemsPerPage;
            const end = start + itemsPerPage;
            const pageData = cachedData.slice(start, end);

            const container = document.getElementById('resultContainer');
            const tableHeader = document.getElementById('tableHeader');
            const tableBody = document.getElementById('tableBody');

            // 清空现有内容
            tableHeader.innerHTML = '';
            tableBody.innerHTML = '';

            if (!pageData || pageData.length === 0) {
                container.style.display = 'none';
                return;
            }

            // 生成表头
            const columns = Object.keys(pageData[0]);
            columns.forEach(column => {
                const th = document.createElement('th');
                th.textContent = column;
                tableHeader.appendChild(th);
            });

            // 显示数据
            pageData.forEach(row => {
                const tr = document.createElement('tr');
                columns.forEach(column => {
                    const td = document.createElement('td');
                    const value = row[column];
                    
                    if (typeof value === 'number') {
                        td.style.textAlign = 'right';
                        td.textContent = value.toLocaleString('zh-CN', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2
                        });
                    } else {
                        td.textContent = value || '-';
                    }
                    
                    tr.appendChild(td);
                });
                tableBody.appendChild(tr);
            });

            // 更新分页
            updatePagination();
            container.style.display = 'block';
        }

        // 更新分页控件
        function updatePagination() {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';

            if (totalPages <= 1) return;

            // 上一页
            const prevButton = document.createElement('button');
            prevButton.textContent = '上一页';
            prevButton.disabled = currentPage === 1;
            prevButton.onclick = () => {
                if (currentPage > 1) {
                    currentPage--;
                    displayPageData();
                }
            };
            pagination.appendChild(prevButton);

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (
                    i === 1 || // 第一页
                    i === totalPages || // 最后一页
                    (i >= currentPage - 2 && i <= currentPage + 2) // 当前页附近
                ) {
                    const pageButton = document.createElement('button');
                    pageButton.textContent = i;
                    pageButton.classList.toggle('active', i === currentPage);
                    pageButton.onclick = () => {
                        currentPage = i;
                        displayPageData();
                    };
                    pagination.appendChild(pageButton);
                } else if (
                    i === currentPage - 3 || // 当前页前的省略号
                    i === currentPage + 3 // 当前页后的省略号
                ) {
                    const ellipsis = document.createElement('span');
                    ellipsis.textContent = '...';
                    ellipsis.className = 'pagination-ellipsis';
                    pagination.appendChild(ellipsis);
                }
            }

            // 下一页
            const nextButton = document.createElement('button');
            nextButton.textContent = '下一页';
            nextButton.disabled = currentPage === totalPages;
            nextButton.onclick = () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    displayPageData();
                }
            };
            pagination.appendChild(nextButton);
        }

        // 修改取消筛选函数
        function cancelFilter() {
            // 清除所有选中状态
            const allCheckboxes = document.querySelectorAll('input[type="checkbox"]');
            allCheckboxes.forEach(cb => {
                cb.checked = false;
            });
            
            // 更新亲属列表
            updateRelativesList();
            
            // 重新加载全量数据
            loadFullData();
        }

        // 绑定按钮事件
        loadDataBtn.addEventListener('click', loadFullData);
        // analyzeDataBtn.addEventListener('click', analyzeData);
        applyFilterBtn.addEventListener('click', applyFilter);
        document.getElementById('cancelFilterBtn').addEventListener('click', cancelFilter);
        
        // 绑定文件夹全选按钮事件
        document.getElementById('selectAllFoldersBtn').addEventListener('click', selectAllFolders);
        document.getElementById('deselectAllFoldersBtn').addEventListener('click', deselectAllFolders);
        
        // 绑定亲属全选按钮事件
        // document.getElementById('selectAllRelativesBtn').addEventListener('click', selectAllRelatives);
        // document.getElementById('deselectAllRelativesBtn').addEventListener('click', deselectAllRelatives);

        // 初始加载数据
        loadFullData();
    });
</script>
{% endblock %} 